/*
 *  $Id: CardManager.cs 1215 2010-11-24 14:50:50Z thenn.erannor $
 *  This file is a part of Ragima CCG.
 *  (C) 2008 Ragima development group.
 *
 *  Licensed under the terms of the GNU GPL License version 2.
 *
 */

using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;

using Nereal.Extensions;

//using Ragima.Serialization;

namespace Ragima {
    public static class CardManager {
        private static Dictionary<Type, Card> cards;
        private static Dictionary<string, Card> cardsById;

        public static void Initialize() {
            cards = new Dictionary<Type, Card>();
            cardsById = new Dictionary<string, Card>();
            foreach (var filename in Directory.GetFiles(Paths.Root, "Ragima.Cards.*.dll")) {
                var assembly = Assembly.LoadFrom(filename);
                FindCards(assembly);
            }
        }

        private static void FindCards(Assembly assembly) {
            foreach (var type in assembly.GetChildTypes(typeof(Card))) {
                if (type.GetConstructor(Type.EmptyTypes) == null)
                    continue;
                var card = (Card) Activator.CreateInstance(type);
                cards.Add(type, card);
                cardsById.Add(card.Id, card);
            }
        }

        public static void Load() {
            for (int i = 0; i < cards.Count; i++)
                Loading.ProgressInc();
        }
        public static int CardsCount { get { return cards.Count; } }

        public static T GetCard<T>() where T: Card { return (T) GetCard(typeof(T)); }
        public static Card GetCard(Type type) {
            return cards.ContainsKey(type) ? cards[type] : null;
        }
        public static Card GetCard(string id) {
            return cardsById.ContainsKey(id) ? cardsById[id] : null;
        }
        public static IEnumerable<Card> GetCards() {
            return cards.Values;
        }
        public static AbilityCard GetAbility<T>() where T: AbilityCard { return GetAbility(typeof(T)); }
        public static AbilityCard GetAbility(Type type) {
            return GetCard(type) as AbilityCard;
        }
        public static AbilityCard GetAbility(string id) {
            return GetCard(id) as AbilityCard;
        }

        public static void Export(string filename, ICardExporter exporter) {
            using (var stream = new FileStream(filename, FileMode.Create))
                exporter.Export(stream, GetCards());
        }
    }
}
